import request from '@/utils/request' // 引入封装的 axios 实例

// 查询所有菜单（优化版，直接返回后端树结构，字段适配前端）
export const getMenuList = async (params = {}) => {
  try {
    const response = await request({
      url: '/permission/select',
      method: 'get',
      params,
    })

    // 兼容不同后端返回结构
    const list = response?.data?.list || response?.data?.data?.list || []

    if (!Array.isArray(list) || list.length === 0) return []

    // 递归处理字段名适配前端
    function adaptTree(arr) {
      return arr.map((item) => {
        const children = item.children ? adaptTree(item.children) : []
        return {
          ...item,
          id: item.permissionId,
          parentId: item.fatherId,
          name: item.permissionName,
          code: item.permissionCode,
          isMenu: item.isMenu,
          children,
        }
      })
    }

    return adaptTree(list)
  } catch (error) {
    console.error('[API Error] 获取菜单列表失败:', error)
    return []
  }
}

// 新增菜单
export const createMenu = (data) => {
  return request({
    url: '/permission/save',
    method: 'post',
    data
  })
}

// 删除菜单
export const deleteMenu = (id) => {
  return request({
    url: '/permission/del',
    method: 'get',
    params: { id }
  })
}
